import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter,Route } from 'react-router-dom';
import FieldList from '../FieldList';
import CardHearder from '../../public/CardHearder';
import { Card, WhiteSpace, Tabs, ActionSheet, Modal,ActivityIndicator,Result,Icon, Tools,PullToRefresh } from 'weaver-mobile';
import { RouteLayout,ListViewPage,TabPage ,Share} from 'weaver-mobile-page';
import ContacterCardStore from '../../../stores/card/ContacterCardStore';
import CustomerCard from '../Customer';
import CustomerMap from '../CustomerMap';
import ContacterForm from '../../form/ContacterForm';
import ContactList from '../../list/ContactList';
import CrmResult from '../CrmResult';
import NoRight from '../../public/NoRight';
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

const alert = Modal.alert;
const getLabel = Tools.getLabel;
// @inject('contacterCardStore')
@withRouter
@observer
export default class ContacterCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      store : new ContacterCardStore(),
      span: [7, 1],
      sharePara:{},
      showAddContact: false
    }
  }

  componentWillMount(){
    const {match,params} = this.props;
    const ps = params ? params : match.params;
    const store = this.state.store;
    let psnew = this.dealWithParam(ps);
    this.setState({
      sharePara: psnew
    })
    store.doNew(this,psnew);
  }
 
  componentDidMount() {
    // const {contacterCardStore} = this.props;
    const store = this.state.store;
    store.doInit();
  }

  componentWillUnmount(){
    // const {contacterCardStore} = this.props;
    const store = this.state.store;
    store.doClear();
  }
  
  render() {
    // const store = this.props.contacterCardStore;
    const store = this.state.store;
    const {initResponsed,initSuccessed,initFailedMsg} = store;
    if(initResponsed){
        if(initSuccessed){
          const {span,showAddContact} = this.state;   
          const {canView,canEdit,tabs,refreshing,fieldItems,title1,title2,title3,concerned,tabPage,id,customerId,customerCardLayout,customerMapLayout,contacterViewAndEditLayout,contactListStore,
          canShare,userId,shareContacterLayout,shareStore,onlyView} = store;
          const tabProps = {
            page:tabPage,
            swipeable:true,
            onChange: (tab) => {
              store.tabChange(tab.key);
            },
          };
          let btns = [];
          btns.push(<Icon type="ellipsis" onClick={this.moreClick.bind(this)}/>);
          if(canView){
            return (        
              <div className="crm-card-base">              
                  <CardHearder title1={title1} title2={title2} title3={title3} concerned={concerned} concernedClick={this.concernedClick.bind(this)} moreClick={this.moreClick.bind(this)} showConcerned={!onlyView?true:false} showMore={false}/>
                  <div className="crm-card-content">
                  {/* <Tabs tabs={tabs}
                    initialPage={tabPage}
                    renderTab={tab => <span>{tab.title}</span>}
                    page={tabPage}
                    onChange={
                      (TabData, index)=>{
                        store.tabChange(index);
                      }
                    }
                  /> */}
                  <TabPage
                    span={span}
                    tabs={tabs}
                    tabProps={tabProps}
                    btns={!onlyView&&btns}
                    // defaultTabBarProps={{ page: 1}}
                    // popover={false}
                    // popoverProps={popoverProps}
                  />
                  <WhiteSpace/>
                  {
                    tabPage == "info" && (
                      <div className="crm-card-main">
                      <PullToRefresh
                        damping={60}
                        // ref={el => this.ptr = el}
                        style={{
                          height: "100%",
                          overflow: 'auto',
                        }}
                        direction={'down'}
                        refreshing={refreshing}
                        onRefresh={() => {
                          store.doInit();
                        }}
                      >
                      <Card full>
                          <Card.Header
                              title={<span style={{marginLeft:"5px",whiteSpace:"nowrap"}}>{getLabel('24893','基础信息')}</span>}
                              extra={<span></span>}
                          >
                          </Card.Header>
                          <Card.Body>
                              <FieldList fieldItems={fieldItems} iconClick={this.iconClick.bind(this)}/>
                              <div className="crm-field-item-bottom"></div>
                          </Card.Body>
                          <Card.Footer content={
                            <div className="crm-card-footer" onClick={() => {
                              this.props.history.push(contacterViewAndEditLayout.path);
                            }}>
                              <div>{getLabel('1293', '查看详细信息')}</div>
                              <div className="crm-field-item-operate"><Icon type={"right"} /></div>
                            </div>
                          } />
                      </Card>                  
                    </PullToRefresh>
                    </div>
                    )
                  }
                  {
                    tabPage == "contact" && (
                      <div className="crm-card-list">
                        <ContactList params={{customerId:customerId,contacterId:id,hideTop:true}} onRef={this.onRef} showAddContact={showAddContact}></ContactList>
                      </div>
                    )
                  }
                </div>
                <Route
                  key={customerCardLayout.id}
                  path={customerCardLayout.path}
                  render={() => {
                    // 客户卡片
                    let detailContent = <CustomerCard params={{id:customerId}} store={store}/>
                    return (
                      <RouteLayout getContainer={() => document.getElementById("root")}>
                        <div
                          key="customerCardLayout"
                          className="wm-route-layout"
                        >                    
                          {detailContent}
                        </div>
                      </RouteLayout>
                    )
                  }}
                />
  
                <Route
                  key={customerMapLayout.id}
                  path={customerMapLayout.path}
                  render={() => {
                    let detailContent = <CustomerMap params={{customerId:customerId}}/>;
                    return (
                      <RouteLayout getContainer={() => document.getElementById("root")}>
                        <div
                          key="customerMapLayout"
                          className="wm-route-layout"
                        >                    
                          {detailContent}
                        </div>
                      </RouteLayout>
                    )
                  }}
                />

                  {/* 分享 */}
           <Route
                key={shareContacterLayout.id}
                path={shareContacterLayout.path}
                render={() => {
                  let shareDialog = 
                   <Share        
                        shareParams={ {
                          'resourcetype' : "67",
                          'resourceid' : id
                        }
                        }
                        store={shareStore }
                        msgInfo={{
                          'content': title1, // 分享标题（必填）
                          'sysid': window.localStorage.emobile_ec_id, //EM中添加的集成系统的ID (必填: 按照demo给的传)                             
                          'linkurl':`/common/chatResource/view.html?resourcetype=67&resourceid=${id}&isfromchatshare=1&sharer=${userId}&firstSharer=${userId}&moduleid=em`,// 消息链接地址（必填） // 消息链接地址（必填）                     
                          'canforward':1, // 消息是否允许转发 1：是（默认） 0：否
                          'callbackurl':"/api/common/chatResource/addshare?resourcetype=67&resourceid="+id+"&isfromchatshare=1&firstSharer="+userId, // 消息转发回调地址（非必填）
                          'sharetypename':getLabel(520328,"联系人名片"), //消息类型显示标题，没有则按sharetype显示
                          'opentype':1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                          'opentype_pc':2, //PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                          'sharetype':"crm", // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                          'shareid':id // 分享的数据ID（必填）
                        
                        } 
                      }                                                           
                   />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="shareContacterLayout"
                        className="wm-route-layout"
                      >
                        {shareDialog}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              {/* end */}
                <Route
                  key={contacterViewAndEditLayout.id}
                  path={contacterViewAndEditLayout.path}
                  render={() => {
                    // 编辑联系人
                    let detailContent = <ContacterForm cardStore={this.props.cardStore} params={{operation:"view",contacterId:id,name:title1,canEdit:canEdit,...this.state.sharePara}}/>
  
                    return (
                      <RouteLayout getContainer={() => document.getElementById("root")}>
                        <div
                          key="contacterViewAndEditLayout"
                          className="wm-route-layout"
                        >                    
                          {detailContent}
                        </div>
                      </RouteLayout>
                    )
                  }}
                />
  
              </div>
            );
          }else{
            return <NoRight />
          }
        }else{
          return (
            <div>
                <CrmResult
                  message={initFailedMsg}
                />
            </div>);
        }
    }else{
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..."/></div>;
    }
  }

  dealWithParam = (ps)=>{
    let psbak = {};
    if(ps.id.lastIndexOf("moduleid")>-1 &&ps.id.lastIndexOf("em_auth_userid") > -1){
      let strs= new Array(); 
      strs=ps.id.split("&"); 
      psbak.id = strs[0];
      for (let i=1;i<strs.length ;i++ ) { 
        let param= new Array(); 
        param=strs[i].split("=");  
        if(param.length >=2){
          psbak[param[0]] = param[1];
        }          
      } 
    }else{
       if("id" in ps){
        psbak.id = ps.id;
      } 
    }
    return psbak;
  
  }
  onRef = (ref) => {
    this.contactListRef = ref;
  }

  // 客户信息操作
  iconClick(itemKey,title,value,valueSpan){
    // const store = this.props.contacterCardStore;
    const store = this.state.store;
    const {customerCardLayout,customerMapLayout} = store;
    if(itemKey == 4){
      this.props.history.push(customerCardLayout.path); 
    }
    if(itemKey == 5){
      // 定位
      this.props.history.push(customerMapLayout.path);
    }
  }

  // 关注 or 取消关注
  concernedClick(concerned){
    // const store = this.props.contacterCardStore;
    const store = this.state.store;
    store.setConcerned(concerned);
  }

  moreClick(){
    // const store = this.props.contacterCardStore;
    const store = this.state.store;
    const {canEdit,contacterViewAndEditLayout,tabPage,canShare,shareContacterLayout} = store;    
    let btns = [];
    btns.push({content: getLabel('390921',"添加联系记录")});
    if(canEdit){
      btns.push({content: getLabel('81299','删除联系人')});      
    }
    if(canShare){
      btns.push({key:2,content: getLabel('126091','分享')});     
    }



    btns.push({content: getLabel('201','取消')});
    ActionSheet.showActionSheetWithOptions({
      options: btns,
      cancelButtonIndex: btns.length - 1,
      // destructiveButtonIndex: BUTTONS.length - 2,
      // title: 'title',
      // message: 'I am description, description, description',
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
    (buttonIndex) => {
      if(buttonIndex == 0){
        // 添加联系记录
        if(tabPage != "contact"){
          store.tabChange("contact");
          this.setState({ showAddContact: true });
          setTimeout(() => {
            this.setState({ showAddContact: false });
          }, 100);
        }else{
          this.contactListRef.addContact();
        }
      }
      if(canEdit){
        if(buttonIndex == 1){
          // 删除联系人
          alert('',getLabel('83600','您确认要删除吗？'),[
              { text: getLabel('201','取消'), onPress: () => {} },
              { text: getLabel('83446','确定'), onPress: () => {store.deleteContacter();} },
          ]);
        }
      }

      if(canShare){
        if(btns[buttonIndex].key == 2){
          this.props.history.push(shareContacterLayout.path);
        }

    }

    });
  }
  
}